import json

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from .models import Department
from staff_management.models import Employee
# Create your views here.
from django.views import View


class DivisionalView(View):
    def get(self, request):
        try:
            dep = Department.objects.all()
        except:
            return JsonResponse({'code': 1001, 'error': '获取失败'})
        print(dep)
        # 获取部门人数?
        # emp = Employee.objects.get(dep_id=dep['dep_id'])

        # 数据封装(json)
        res = self.get_dep_by_request(dep)
        return JsonResponse(res)

    def post(self, request):
        json_str = request.body
        py_obj = json.loads(json_str)
        print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')
        print(py_obj)
        dep_name = py_obj['dep_name']
        dep_id = py_obj['dep_id']
        department_head = py_obj['department_head']
        department_head_id = py_obj['department_head_id']

        try:
            dep = Department.objects.create(dep_id=dep_id,dep_name=dep_name,department_head_id=department_head_id,
                                            is_active=1)
        except:
            return JsonResponse({'code':1000,'error':'添加失败'})

        return JsonResponse({'code': 200})

    def get_dep_by_request(self, dep):
        j_list = []
        for d in dep:
            j_dict = {}
            j_dict['dep_name'] = d['dep_name']
            j_dict['dep_id'] = d['dep_id']
            j_dict['department_head'] = d['department_head']
            j_dict['department_head_id'] = d['department_head_id']
            j_list.append(j_dict)
        res = {'code': 200, 'data': {}}
        # res = ['data']['dep_data'] = j_list
        return res
